package com.imau.controller;

import com.alibaba.fastjson.JSON;
import com.imau.common.entiry.ResultEntity;
import com.imau.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
 public class Baseconterllor  extends HttpServlet {

     private static final Logger logger = LoggerFactory.getLogger(Baseconterllor.class);

    protected BaseService service;

    public Baseconterllor(BaseService service)
    {
        this.service = service;
    }

    public Baseconterllor()
    {

    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //http://localhost/brand-demo/brand student/操作add,update ,delete get getAll


        /*1.获取请求的地址*/
        String uri = request.getRequestURI();

        /*2.截取请求地址中的 方法add,update ,delete get getAll*/
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);


        /*3.反射调用*/
        Method method = null;

        try {

            method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);

        } catch (Exception e) {


            logger.error("访问方法系统反射异常=",e.getMessage());

            throw  new RuntimeException();

        }

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }


    protected void responseBody(HttpServletResponse response, boolean b,ResultEntity result) throws IOException {

        PrintWriter writer = response.getWriter();

        if(b)
        {
            writer.write(JSON.toJSONString(result));

        }else {

            writer.write(JSON.toJSONString(ResultEntity.FAIL()));
        }


    }


     protected void responseBody(HttpServletResponse response, boolean b,ResultEntity successresult,ResultEntity errorresult) throws IOException {

         PrintWriter writer = response.getWriter();

         if(b)
         {
             writer.write(JSON.toJSONString(successresult));

         }else {

             writer.write(JSON.toJSONString(errorresult));
         }


     }
}
